<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="协议ID" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入协议ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="协议名称" prop="protocolName">
        <el-input
          v-model="queryParams.protocolName"
          placeholder="请输入协议名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="协议类型" prop="protocolType">
        <el-select v-model="queryParams.protocolType" placeholder="请选择协议类型" clearable>
          <el-option
            v-for="dict in dict.type.iot_protocol_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="发布状态" prop="publishState">
        <el-select v-model="queryParams.publishState" placeholder="请选择发布状态" clearable>
          <el-option
            v-for="dict in dict.type.iot_publish_state"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['iot:protocol:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['iot:protocol:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['iot:protocol:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table ref="protocolTable" v-loading="loading" :data="protocolList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="协议ID" align="center" prop="id" />
      <el-table-column label="协议名称" align="center" prop="protocolName" />
      <el-table-column label="协议类型" align="center" prop="protocolType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.iot_protocol_type" :value="scope.row.protocolType"/>
        </template>
      </el-table-column>
      <el-table-column label="发布状态" align="center" prop="publishState">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.publishState"
            :active-value=1
            :inactive-value=0
            @change="handlePublishStateChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="描述" align="center" prop="description" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['iot:protocol:edit']"
          >修改</el-button>
          <el-button
            v-if="scope.row.publishState === 0"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['iot:protocol:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改协议对话框 -->
    <el-drawer
      :wrapperClosable="false"
      :title="title"
      :visible.sync="open"
      direction="rtl"
    >
      <el-container>
        <el-main>
          <el-form ref="form" :model="form" :rules="rules"  label-width="80px">

            <!-- 协议ID -->
            <el-form-item label="协议ID" prop="id">
              <el-input v-model="form.id" placeholder="请输入协议ID" :disabled="isUpdate"/>
            </el-form-item>

            <!-- 协议名称 -->
            <el-form-item label="协议名称" prop="protocolName">
              <el-input v-model="form.protocolName" placeholder="请输入协议名称" />
            </el-form-item>

            <!-- 协议类型 -->
            <el-form-item label="协议类型" prop="protocolType">
              <el-select v-model="form.protocolType" placeholder="请选择协议类型" :disabled="formDisabledByPublishState" class="select-width">
                <el-option
                  v-for="dict in dict.type.iot_protocol_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>

            <!-- 类名 -->
            <el-form-item v-if="providerVisible" label="类名" prop="configuration.provider">
              <el-input v-model="form.configuration.provider" :disabled="formDisabledByPublishState" placeholder="请输入类名" />
            </el-form-item>

            <el-row>
              <el-col :span="17">
                <!-- 文件地址 -->
                <el-form-item v-if="locationVisible" label="文件地址" prop="configuration.location">
                  <el-input disabled v-model="form.configuration.location" />
                </el-form-item>
              </el-col>

              <el-col :offset="1" :span="5">
                <!-- 上传jar包 -->
                <file-upload
                  :disabled="formDisabledByPublishState"
                  v-show="locationVisible"
                  :file-type="fileType"
                  :file-url="fileUrl"
                  :show-file-list="false"
                  :is-show-tip="false"
                  icon="el-icon-upload2"
                  @input="handleFileInput"
                  size=""
                >上传jar包</file-upload>
              </el-col>
            </el-row>

            <!-- 协议标识 -->
            <el-form-item v-if="protocolVisible" label="协议标识" prop="configuration.protocol">
              <el-input v-model="form.configuration.protocol" :disabled="formDisabledByPublishState" />
            </el-form-item>

            <!-- 连接协议 -->
            <el-form-item v-if="transportVisible" label="连接协议" prop="configuration.transport">
              <el-select
                :disabled="formDisabledByPublishState"
                v-model="form.configuration.transport"
                multiple
                filterable
                default-first-option
                class="select-width"
                placeholder="请选择连接协议">
                <el-option
                  v-for="item in dict.type.iot_transport_protocol"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>

            <!-- 脚本 -->
            <el-form-item v-show="scriptVisible" label="脚本">
              <editor
                v-model="form.configuration.script"
                @init="editorInit"
                lang="javascript"
                theme="chrome"
                height="400"
                :options="editorOptions"
              />
            </el-form-item>

            <!-- 描述 -->
            <el-form-item label="描述" prop="description">
              <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
            </el-form-item>

          </el-form>

        </el-main>
        <el-footer>
          <div class="bottom-bar" style="text-align: right">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
          </div>
        </el-footer>
      </el-container>
    </el-drawer>

  </div>
</template>

<script>
import {
  listProtocol,
  getProtocol,
  delProtocol,
  addProtocol,
  updateProtocol,
  deployProtocol,
  undeployProtocol
} from '@/api/iot/protocol'
import Editor from "vue2-ace-editor";

export default {
  name: "Protocol",
  components:{
    Editor
  },
  dicts: [
    'iot_protocol_type',
    'iot_publish_state',
    'iot_transport_protocol'
  ],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 协议表格数据
      protocolList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: null,
        protocolName: null,
        protocolType: null,
        publishState: null,
      },
      // 表单参数
      form: {
        configuration: {}
      },

      // 类名输入框默认隐藏
      providerVisible: false,
      // 文件地址输入框默认隐藏
      locationVisible: false,
      // 协议标识输入框默认隐藏
      protocolVisible: false,
      // 连接协议输入框默认隐藏
      transportVisible: false,
      // 脚本入框默认隐藏
      scriptVisible: false,
      // 是否是更新操作
      isUpdate: false,

      // 表单校验
      rules: {
        id: [
          { required: true, message: "协议ID不能为空", trigger: "blur" }
        ],
        protocolName: [
          { required: true, message: "协议名称不能为空", trigger: "blur" }
        ],
        protocolType: [
          { required: true, message: "协议类型不能为空", trigger: "change" }
        ],
        publishState: [
          { required: true, message: "发布状态不能为空", trigger: "change" }
        ],
        configuration: {
          provider: [
            { required: true, message: "类名不能为空", trigger: "change" }
          ],
          location: [
            { required: true, message: "文件地址不能为空", trigger: "change" }
          ],
          protocol: [
            { required: true, message: "协议标识不能为空", trigger: "change" }
          ],
          transport: [
            { required: true, message: "连接协议不能为空", trigger: "change" }
          ],
        }
      },
      // 上传文件类型
      fileType: ['jar'],
      // 文件上传路径
      fileUrl: '/iot/protocol/file',
      editorOptions: {
        // 设置代码编辑器的样式
        enableBasicAutocompletion: true, //启用基本自动完成
        enableSnippets: true, // 启用代码段
        enableLiveAutocompletion: true, //启用实时自动完成
        tabSize: 2, //标签大小
        fontSize: 14, //设置字号
        showPrintMargin: false, //去除编辑器里的竖线
        readOnly: false, // 是否只读
      },
    }
  },
  computed: {
    formDisabledByPublishState() {
      const disabled = this.form.publishState === 1
      this.editorOptions.readOnly = disabled
      return disabled
    }
  },
  watch: {
    'form.protocolType'(type) {
      this.visibleByProtocolType(type);
    },
    // 重置类名输入框
    providerVisible(value) {
      if (!value) {
        this.$set(this.form.configuration, 'provider', undefined);
      }
    },
    // 重置文件地址输入框
    locationVisible(value) {
      if (!value) {
        this.$set(this.form.configuration, 'location', undefined);
      }
    },
    // 重置协议标识输入框
    protocolVisible(value) {
      if (!value) {
        this.$set(this.form.configuration, 'protocol', undefined);
      }
    },
    // 重置协连接协议输入框
    transportVisible(value) {
      if (!value) {
        this.$set(this.form.configuration, 'transport', undefined);
      }
    },
    // 监听脚本输入框显示与隐藏
    scriptVisible(value) {
      if (value) {
        // 显示时表单数据添加语言类型
        this.form.configuration.lang = 'js';
      }else {
        // 隐藏时表单数据清除语言类型
        this.form.configuration.lang = undefined;
      }
    }
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询协议列表 */
    getList() {
      this.loading = true;
      listProtocol(this.queryParams).then(response => {
        this.protocolList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        configuration: {},
        protocolName: null,
        id: null,
        protocolType: null,
        publishState: null,
        description: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      selection.forEach(row => {
        if (row.publishState === 1) {
          this.$refs.protocolTable.toggleRowSelection(row);
        }
      });
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加协议";
      this.isUpdate = false;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getProtocol(id).then(response => {
        let data = response.data;
        data.configuration = JSON.parse(data.configuration)
        this.form = data;
        this.open = true;
        this.title = "修改协议";
        this.isUpdate = true;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let form = JSON.parse(JSON.stringify(this.form))
          form.configuration = JSON.stringify(form.configuration);
          if (this.isUpdate) {
            updateProtocol(form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            // 发布状态默认为0为发布
            form.publishState = 0;
            addProtocol(form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除协议ID为"' + ids + '"的数据项？').then(function() {
        return delProtocol(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('iot/protocol/export', {
        ...this.queryParams
      }, `protocol_${new Date().getTime()}.xlsx`)
    },
    /**
     * 发布状态修改
     */
    handlePublishStateChange(row) {
      let text = row.publishState === 1 ? "发布" : "取消";
      this.$modal.confirm(`确认要${text}${row.protocolName}协议吗？`).then(function() {
        if (row.publishState === 1) { deployProtocol(row.id) }
        if (row.publishState === 0) { undeployProtocol(row.id) }
      }).then(() => {
        this.$modal.msgSuccess( `${text}成功`);
      }).catch(() => {
        row.publishState = row.publishState === 0 ? 1 : 0;
      });
    },
    /**
     * 根据协议类型显示隐藏表单
     * @param type 协议类型
     */
    visibleByProtocolType(type) {
      if (!type) {

        // 隐藏 类名输入框默认
        this.providerVisible = false;
        // 隐藏 文件地址输入框
        this.locationVisible = false;

        // 隐藏 协议标识输入框
        this.protocolVisible = false;
        // 隐藏 连接协议输入框
        this.transportVisible = false;
        // 隐藏 脚本入框
        this.scriptVisible = false;

        return
      }

      if (type === 'jar') {

        // 隐藏 协议标识输入框
        this.protocolVisible = false;
        // 隐藏 连接协议输入框
        this.transportVisible = false;
        // 隐藏 脚本入框
        this.scriptVisible = false;

        // 显示 类名输入框默认
        this.providerVisible = true;
        // 显示 文件地址输入框
        this.locationVisible = true;

        return;
      }

      if (type === 'script') {

        // 隐藏 类名输入框默认
        this.providerVisible = false;
        // 隐藏 文件地址输入框
        this.locationVisible = false;

        // 显示 协议标识输入框
        this.protocolVisible = true;
        // 显示 连接协议输入框
        this.transportVisible = true;
        // 显示 脚本入框
        this.scriptVisible = true;
      }

    },

    /**
     * 获取文件地址
     * @param fileAddress
     */
    handleFileInput(fileAddress) {
      fileAddress = fileAddress.split(',');
      fileAddress = fileAddress[fileAddress.length - 1]
      fileAddress = fileAddress.replace('/profile/protocol', '');
      // 文件地址输入框赋值
      this.$set(this.form.configuration, 'location', fileAddress);
    },
    editorInit() {
      require('brace/ext/language_tools') // language extension prerequsite...
      require('brace/mode/javascript')    // language
      require('brace/theme/chrome')
      require('brace/snippets/javascript') // snippet
    }
  }
};
</script>

<style lang="scss" scoped>

</style>
